package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"sync"

	"github.com/gin-gonic/gin"
)

type Config struct {
	EnableForward bool   `json:"enable_forward"`
	TargetHost    string `json:"target_host"`
	TargetPort    string `json:"target_port"`
	mu            sync.RWMutex
}

var (
	config = &Config{
		EnableForward: ENABLE_FORWARD,
		TargetHost:    TARGET_HOST,
		TargetPort:    TARGET_PORT,
	}
)

// 启动Web服务
func startWebServer(port int) {
	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()

	// 设置模板
	r.LoadHTMLGlob("templates/*")
	r.Static("/static", "./static")

	// 首页
	r.GET("/", func(c *gin.Context) {
		config.mu.RLock()
		defer config.mu.RUnlock()
		c.HTML(http.StatusOK, "index.html", gin.H{
			"enable_forward": config.EnableForward,
			"target_host":    config.TargetHost,
			"target_port":    config.TargetPort,
		})
	})

	// 获取配置
	r.GET("/api/config", func(c *gin.Context) {
		config.mu.RLock()
		defer config.mu.RUnlock()
		c.JSON(http.StatusOK, config)
	})

	// 更新配置
	r.POST("/api/config", func(c *gin.Context) {
		var newConfig Config
		if err := c.BindJSON(&newConfig); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		config.mu.Lock()
		config.EnableForward = newConfig.EnableForward
		config.TargetHost = newConfig.TargetHost
		config.TargetPort = newConfig.TargetPort
		config.mu.Unlock()

		// 更新全局变量
		updateGlobalConfig(newConfig)

		c.JSON(http.StatusOK, gin.H{"status": "success"})
	})

	// 获取日志
	r.GET("/api/logs", func(c *gin.Context) {
		logDir := "logs"
		files, err := ioutil.ReadDir(logDir)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		var logFiles []string
		for _, file := range files {
			if strings.HasSuffix(file.Name(), ".log") {
				logFiles = append(logFiles, file.Name())
			}
		}

		c.JSON(http.StatusOK, gin.H{"files": logFiles})
	})

	// 获取日志内容
	r.GET("/api/logs/:filename", func(c *gin.Context) {
		filename := c.Param("filename")
		content, err := ioutil.ReadFile(filepath.Join("logs", filename))
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.String(http.StatusOK, string(content))
	})

	// 服务器控制
	r.POST("/api/control/:action", func(c *gin.Context) {
		action := c.Param("action")
		switch action {
		case "restart":
			// 重启服务器
			os.Exit(0) // 让外部脚本重启服务
		case "stop":
			// 停止服务器
			os.Exit(0)
		default:
			c.JSON(http.StatusBadRequest, gin.H{"error": "invalid action"})
			return
		}
		c.JSON(http.StatusOK, gin.H{"status": "success"})
	})

	// 启动Web服务
	go func() {
		addr := fmt.Sprintf(":%d", port)
		if err := r.Run(addr); err != nil {
			log.Printf("Web服务启动失败: %v", err)
		}
	}()
}

// 更新全局配置
func updateGlobalConfig(newConfig Config) {
	if globalServer != nil {
		globalServer.UpdateConfig(newConfig.EnableForward, newConfig.TargetHost, newConfig.TargetPort)
		log.Printf("配置已更新: EnableForward=%v, TargetHost=%s, TargetPort=%s",
			newConfig.EnableForward, newConfig.TargetHost, newConfig.TargetPort)
	} else {
		log.Printf("错误: 服务器实例未初始化")
	}
} 